﻿// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;

namespace SnapObjects.Data.SqlServer
{
    internal class SqlServerFunctionParameterSchemaProvider : SqlServerRoutineParameterSchemaProvider
    {
        public SqlServerFunctionParameterSchemaProvider(DataContext dataContext) : base(dataContext)
        {
        }

        protected override ProcedureSchema CreateParameterSchema(
            string name,
            IReadOnlyList<AdoDbParameter> adoDbParameters,
            IReadOnlyList<DynamicModel> dbParameters)
        {
            var parameter = dbParameters.FirstOrDefault();

            var returnType = FunctionReturnType.Scalar;

            if (parameter != null)
            {
                var type = parameter.GetValue<string>("type");

                if ("TF".Equals(type, StringComparison.OrdinalIgnoreCase))
                {
                    returnType = FunctionReturnType.Table;
                }
            }

            return new ProcedureSchema(name, adoDbParameters, returnType);
        }

        protected override string GetSchemaQuerySql(string database, string condition)
        {
            string schemaQuerySql = @"
SELECT obj.object_id as object_uniqueidentifier,
       parm.name as parameter_name,
	   t.name as parameter_datatype,
	   CASE parm.is_output WHEN 1 THEN 'OUT' ELSE 'IN' END as parameter_mode,
	   parm.precision as parameter_precision,
	   parm.scale as parameter_scale,
       parm.default_value as parameter_defaultvalue,
       obj.type as type
  FROM {0}sys.all_objects obj 
 INNER JOIN {0}sys.schemas sm
    ON obj.schema_id = sm.schema_id
  LEFT JOIN {0}sys.all_parameters parm
    ON obj.object_id = parm.object_id
  LEFT JOIN {0}sys.types t
    ON t.user_type_id = parm.user_type_id and t.system_type_id = parm.system_type_id
 WHERE (obj.type='FN' or obj.type='TF')
   AND {1}
 ORDER BY parm.parameter_id";

            database = !String.IsNullOrWhiteSpace(database) ? $"{database}." : String.Empty;

            return String.Format(schemaQuerySql, database, condition);
        }

        protected override string IsRoutineDefinedInCurrentSchemaSql(string database, string procedureName)
        {
            var sql = @" 
SELECT name 
  FROM {0}sys.all_objects 
 WHERE name = '{1}' 
   AND schema_id = SCHEMA_ID() 
   AND type='FN' or type='TF'";

            database = !String.IsNullOrWhiteSpace(database) ? $"{database}." : String.Empty;

            return String.Format(sql, database, procedureName);
        }
    }
}
